<template>
  <view class="Choose">
    <view style="margin-bottom: 80rpx;padding: 40rpx;">
		<view class="formdata" style="margin: 0 30rpx;">
			<view class="formdata-item">
				<view class="text">
					<text>专业班级</text>
				</view>
				<view class="input">
					<input placeholder="请输入专业班级" @input="queryProfessionalClass"/>
				</view>
			</view>
		</view>
      <view class="cu-card" :id="`card-${item.CLASS_ID}`" v-for="item in allClassList" :key="item.CLASS_ID" :data-id="item.CLASS_ID">
        <view class="cu-item shadow padding card-item" style="margin-top: 20rpx;margin-bottom: 10rpx;">
          <view class="cu-tag bg-green sm" v-if="item.SH_FLAG == '1'">需审核</view>
		  <view class="cu-tag bg-green sm" v-if="item.SH_FLAG == '0'">无需审核</view>
          <view class="cu-list menu">
            <view class="cu-item">
              <!--                <view class="cu-avatar round lg" style="background-image:url(https://ossweb-img.qq.com/images/lol/web201310/skin/big10006.jpg);"></view>-->
              <view class="content flex-sub">
                <view class="text-black text-bold">{{ item.CLASSNAME }}</view>
				<view class="text-gray text-lg flex">
				  <text>课任老师姓名： {{ item.TEACHERNAME}}</text>
				</view>
                <view class="text-gray text-lg flex">
                  <text>专业： {{item.MAJOR_NAME}}</text>
                </view>
                <view class="text-gray text-lg flex">
                  <text>开课时间： {{item.S_KK_DATE}}</text>
                </view>

                <view class="text-gray text-lg flex">
                  <text>上课时间： {{ item.SKSJSNR}}</text>
                </view>

                



								<view class="text-gray text-lg">
								  <text>审核状态：</text><view class="cu-tag bg-green sm" v-if="item.CBSH_FLAGNR" style="position: relative;">{{item.CBSH_FLAGNR}}</view>
								</view>
								<view class="text-gray text-lg " >
								  <text>报名表状态：</text><view class="cu-tag bg-green sm" v-if="item.CBSTATENR" style="position: relative;">{{item.CBSTATENR}}</view>
								</view>
                <view class="text-gray text-lg flex margin-tb-xs">
                  <view class="cu-tag radius bg-red light" style="position: relative;margin-left: 0">{{ item.DSZ_FLAGNR }}</view>
                </view>

              </view>
            </view>

            <view class="cu-item">
              <view class="flex flex-direction text-red text-df">
                <view class="text-price">{{ getPrice(+item.SFJE1,false) }}<text class="text-lg margin-left-xs text-gray">低于50周岁</text></view>
                <view class="text-price">{{ getPrice(+item.SFJE2,false) }}<text class="text-lg margin-left-xs text-gray">50周岁（含）以上</text></view>
                <view class="text-lg text-red margin-tb-xs" v-if="item.QXXZ_FLAG != '1'">不可取消</view>
              </view>
              <checkbox-group @change="onCheckChange" :data-id="item.CLASS_ID">
                <checkbox :disabled="selectedIds.includes(item.CLASS_ID) && item.QXXZ_FLAG != '1'" class="round blue" :value="item.CLASS_ID" :checked="selectedIds.includes(item.CLASS_ID)"></checkbox>
              </checkbox-group>

            </view>
          </view>
        </view>
      </view>
      <load-more :status="loadStatus"/>
    </view>
  </view>

  <view class="flex justify-center margin-bottom">
    <button class="cu-btn round block bg-blue float-btn shadow" @tap="confirmEnroll">确认选择</button>
  </view>
</template>

<script lang="ts" setup>
import {onLoad} from "@dcloudio/uni-app";
import {FetchKXClassListDAT} from "../../types/responseTypes";
import LoadMore from '../../components/loadmore/index.vue'
import {computed, ref, toRefs, watchEffect} from "vue";
import {useClasses} from "../index/useClasses";
import {usePagination} from "../../utils/usePagination";
import {usePrice} from "../../utils/usePrice";
import {useStore} from "vuex";

const Zlselect = ref<any>([])
onLoad((option:any)=>{
	Zlselect.value = JSON.parse(decodeURIComponent(option.ZL))
	uni.showModal({
		title: '注意事项',
		content: '上课时间冲突的课程，只能勾选一个，所以大家在选课程时，请优先勾选一定要就读的课程，再去勾选其它课程',
		success: res => {},
		fail: () => {},
		complete: () => {}
	})
})

interface ChooseProps {
  ZL: any,
  // enrollData: any
}

const allClassList = computed(() => {
	let selectedClassList:any = []
	let notSelectedClassList:any = []
	let filClassList:any = []
	for(let i = 0; i<classList.value.length; i++){
		if(selectedIds.value.includes(classList.value[i].CLASS_ID)){
			selectedClassList.push(classList.value[i])
		} else{
			notSelectedClassList.push(classList.value[i])
		}
	}
	filClassList = notSelectedClassList.filter((item) => {
		 return item.CLASSNAME.indexOf(keyWord.value) != -1
	})
	return [...selectedClassList,...filClassList]
	
	
	
})
const keyWord = ref('')
const props = withDefaults(defineProps<ChooseProps>(),{})
const ZL: FetchKXClassListDAT[] = JSON.parse(decodeURIComponent(props.ZL))
// const enrollData: UserEnrollListDAT = JSON.parse(decodeURIComponent(props.enrollData))
const selectedIds = ref<number[]>(ZL.map(item => item.CLASS_ID))
const pageSize = 20
const {classList, initClassList,total} = useClasses()

function pageScrollTo(id: any|string|number){
  if(!id.value){
    return
  }
  let selector = "#card-"+id.value
  setTimeout(() => {
      uni.pageScrollTo({
        selector: selector,
        duration: 0,
      })
    })
}

const {page,loadStatus,argsAfter} = usePagination({
  page: 1,
  pageSize,
  onPageChange: initClassList,
  onPageAfter: pageScrollTo,
  argsAfter: '',
  startReachBottom: true,
  args: computed(() => selectedIds.value.join(';'))
})

watchEffect(() => {
  loadStatus.value = total.value <= pageSize ? 'over' : 'loadmore'
})

// const chooseList = computed(() => props.ZL.concat(classList.value as []))

const {getPrice} = usePrice()

function refreshClassList(id: any) {
  classList.value.length = 0
  // 为了触发响应式更新
  page.value = -100
  page.value = 1
  argsAfter.value = id
  loadStatus.value = 'loadmore'
}

function onCheckChange(e: any){
  const id = e.currentTarget.dataset.id
  if (e.detail.value[0] ){
    selectedIds.value.push(id)
    refreshClassList(id)
  }else {
    
    const target = classList.value.find(item => item.CLASS_ID == id)
    if (target?.QXXZ_FLAG == '1'){
      selectedIds.value.splice(selectedIds.value.indexOf(id),1)
      refreshClassList(selectedIds.value[selectedIds.value.length - 1])
      
    }else {
      uni.showToast({
        title: '当前课程无法取消',
        icon: 'none',
        mask: true
      })
    }

  }
}

const {USERNO,USERNAME,CUSER_ID} = toRefs(useStore().state.user.userInfo)

function confirmEnroll(){
  uni.showModal({
    title: '提示',
    content: '是否确定选择？',
    success: async ({confirm}) => {
      if (confirm){
        uni.$emit('choose',classList.value.filter(item => selectedIds.value.includes(item.CLASS_ID)))
        uni.navigateBack()
        // try {
        //   const res = await updateEnrollForm({
        //     ...enrollData,
        //     USERNO: USERNO.value,
        //     USERNAME: USERNAME.value,
        //     OPERATOR_ID: CUSER_ID.value
        //   })
        //
        //   if (res.ERROR[0].errcode == '0'){
        //     uni.$emit('updateCourse')
        //     uni.showToast({
        //       title: '提交成功',
        //       icon: 'success',
        //       mask: true
        //     })
        //
        //     setTimeout(() => {
        //       uni.navigateBack()
        //     },500)
        //   }else {
        //     uni.showToast({
        //       title: res.ERROR[0].error,
        //       icon: 'none',
        //       mask: true
        //     })
        //   }
        // }catch (err){
        //   console.log(err)
        //   uni.showToast({
        //     title: '提交失败',
        //     icon: 'error',
        //     mask: true
        //   })
        // }
      }
    }
  })
}

function queryProfessionalClass(e){
	keyWord.value = e.detail.value
}
</script>

<style scoped lang="scss">
.Choose{
  box-sizing: border-box;
  padding-bottom: constant(safe-area-inset-bottom);  ///兼容 IOS<11.2/
  padding-bottom: env(safe-area-inset-bottom);  ///兼容 IOS>11.2/

  .card-item{
    position: relative;
    .cu-tag{
      position: absolute;
      right: 0;
      z-index: 2;
    }
  }
}
.formdata {
	background-color: white;
		.formdata-item {
			padding: 0 32rpx 0 32rpx;
			border-bottom: 4rpx #F7F8FC solid;
			width: 100%;
			height: 80rpx;
			display: flex;
			align-items: center;

			.text {
				margin-right: 32rpx;
			}
		}
	}
</style>
